package com.tsd.core.aspect;

import com.tsd.core.annotation.DataSource;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.utils.ExceptionUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author Luoyc
 * @Date 2018/12/11 16:44
 * @Version
 * @Description: 更加注解值切换数据源切面
 */
@Order(1)
@Aspect
@Component
public class DataSourceAspect {

    public static final Logger LOGGER = LoggerFactory.getLogger(DataSourceAspect.class);

    @Before("@annotation(source)")
    public void beforeSwitchDataSource(JoinPoint point, DataSource source) {
        DataSourceContextHolder.clearDataSourceType();
        //获得当前访问的class
        Class<?> className = point.getTarget().getClass();
        //获得访问的方法名
        String methodName = point.getSignature().getName();
        //得到方法的参数的类型
        Class<?>[] argClass = ((MethodSignature) point.getSignature()).getParameterTypes();
        String dataSource = DataSourceContextHolder.DEFAULT_ACCOUNT_SET_SID;
        try {
            //得到访问的对象方法
            Method method = className.getMethod(methodName, argClass);
            //判断是否存在@DataSource注解
            if (method.isAnnotationPresent(DataSource.class)) {
                //取出注解中的数据源名
                dataSource = source.value();
            }
        } catch (Exception e) {
            LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
        }
        //切换数据源
        DataSourceContextHolder.setDataSourceType(dataSource);
    }
}
